﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tasks.Common;
using Tasks.Common.Entitys;
using Tasks.Business;
using System.Net.Mail;
using MyLib.Util;

namespace Tasks.Core
{
    public class TaskService
    {
        public enum TaskNoticeType
        {
            None = 0,
            /// <summary>
            /// 测试通过
            /// </summary>
            Pass = 1,
            /// <summary>
            /// 测试不通过
            /// </summary>
            NoPass = 2,
            /// <summary>
            /// 回复任务
            /// </summary>
            Reply = 3,
            /// <summary>
            /// 添加子任务
            /// </summary>
            ChildTask = 4,
            ApplyTest = 5
        }



        /// <summary>
        /// 通知任务相关人员
        /// </summary>
        /// <param name="articleID"></param>
        public static void NoticeTaskUser(int articleID, TaskNoticeType noticeType)
        {
            ArticleBLL artBLL = new ArticleBLL();
            Article article = artBLL.GetArticleByID(articleID);

            IList<Account> mailList = new List<Account>();
            string mailContent = "";
            string subject = "";
            string title = "";

            #region "提取需要通知的人EMAIL"

            if (article.ReplyID != 0) //回复任务
            {
                article = artBLL.GetArticleByID(article.ReplyID);
                subject = "【回复】";
            }
            else if (article.ParentID != 0)
            {
                Article parentArticle = artBLL.GetArticleByID(article.ParentID);
                subject = "【子任务】" + parentArticle.Title + " ==> ";
                title = parentArticle.Title + " ==> " + article.Title;
            }
            else
            {
                subject = "【任务】";
            }

            switch (noticeType)
            {
                case TaskNoticeType.NoPass:
                    subject = "【测试不通过】";
                    break;
                case TaskNoticeType.Pass:
                    subject = "【测试通过】";
                    break;
                case TaskNoticeType.ApplyTest:
                    subject = "【申请测试】";
                    break;
            }

            #endregion

            Account acc1 = BusinessFactory.Account.GetAccount(article.OperatorID);
            Account acc2 = BusinessFactory.Account.GetAccount(article.CreateUserID);
            mailList.Add(acc1);
            mailList.Add(acc2);

            #region "格式化EMAIL内容"

            subject += article.Title;

            mailContent += "标题:" + title;
            mailContent += "<br/>";
            mailContent += "状态:" + article.StateStr();
            mailContent += "<br/>";
            mailContent += "-------------------------------------------------------------------";
            mailContent += "<br/>";
            mailContent += "提交人:" + article.CreateUserName;
            mailContent += "<br/>";
            mailContent += "处理人:" + article.OperatorName;
            mailContent += "<br/>";
            mailContent += "项目:" + article.ProjectIDStr();
            mailContent += "<br/>";
            mailContent += "计划时间:" + article.PlanStartTime.Value.ToString() + " 至 " + article.PlanEndTime.Value.ToString();
            mailContent += "<br/>";
            mailContent += "-------------------------------------------------------------------";
            mailContent += "<br/>";
            mailContent += "内容:";
            mailContent += "<br/>";
            mailContent += StringUtil.CharToHtml(article.Content);
            mailContent += "<br/>";
            mailContent += "-------------------------------------------------------------------";
            mailContent += "<br/>";
            mailContent += "回复:";

            IList<Article> replyArticles = artBLL.GetArticleByReplyID(article.ID);
            foreach (Article replyArticle in replyArticles)
            {
                mailContent += "<br/>";
                mailContent += replyArticle.CreateUserName + "  " + replyArticle.CreateTime;
                mailContent += "<br/>";
                mailContent += replyArticle.Content;
            }
            mailContent += "<br/>";
            mailContent += "-------------------------------------------------------------------";
            mailContent += "<br/>";
            mailContent += "子任务:";
            mailContent += "<br/>";

            IList<Article> childArticles = artBLL.GetArticleByParentID(article.ID);
            foreach (Article childArticle in childArticles)
            {
                mailContent += "<br/>";
                mailContent += childArticle.CreateUserName + "  " + childArticle.CreateTime;
                mailContent += "<br/>";
                mailContent += childArticle.Title;
            }

            #endregion

            #region "发送EMAIL"

            foreach (Account acc in mailList)
            {
                if (acc != null && !string.IsNullOrWhiteSpace(acc.EMail))
                {
                    SendMail(subject, mailContent, acc.EMail, acc.Name);
                }
            }

            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="articleID"></param>
        /// <param name="testResult"></param>
        /// <param name="tester"></param>
        /// <returns></returns>
        public static ExecuteResult UpdateTestResult(int[] articleID, TestResult testResult, string tester)
        {
            ArticleBLL artBLL = new ArticleBLL();
            artBLL.UpdateTestResult(articleID, testResult, tester);

            //发通知
            foreach (int id in articleID)
            {
                TaskNoticeType noticeType = TaskNoticeType.NoPass;

                #region "记录日志"

                Article logArt = new Article();
                logArt.ReplyID = id;
                logArt.CreateUserName = tester;

                switch (testResult)
                { 
                    case TestResult.ApplyTest:
                        logArt.Content = "申请测试";                       
                        noticeType = TaskNoticeType.ApplyTest;
                        break;
                    case TestResult.NoPass:
                        logArt.Content = "测试不通过";    
                        noticeType = TaskNoticeType.NoPass;
                        break;
                    case TestResult.Pass:
                        logArt.Content = "测试通过";    
                        noticeType = TaskNoticeType.Pass;
                        break;                
                }

                new ArticleBLL().CreateArticle(logArt);

                #endregion

                NoticeTaskUser(id, noticeType);
            }

            return new ExecuteResult() { ResultNo = 1 };
        }


        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public static ExecuteResult CreateTask(Article article)
        {
            ArticleBLL artBLL = new ArticleBLL();
            ExecuteResult result = artBLL.CreateArticle(article);

            if (result.ResultNo == 1)
            {
                NoticeTaskUser(article.ID, TaskNoticeType.None);
            }

            return result;
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public static ExecuteResult ModifyTask(Article article)
        {
            ArticleBLL artBLL = new ArticleBLL();
            ExecuteResult result = artBLL.ModifyArticle(article);

            if (result.ResultNo == 1)
            {
                NoticeTaskUser(article.ID, TaskNoticeType.None);
            }

            return result;
        }

        /// <summary>
        /// 发送EMAIL
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="mailContent"></param>
        /// <param name="ToMail"></param>
        /// <param name="toName"></param>
        public static void SendMail(string subject, string mailContent, string ToMail, string toName)
        {
            try
            {
                string fromMail = Config.MailHost;
                string mailPwd = Config.mailPassword;

                System.Net.Mail.SmtpClient client = new SmtpClient("smtp.qq.com");
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential(fromMail, mailPwd);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailAddress addressFrom = new MailAddress(fromMail, "自游技术部");
                MailAddress addressTo = new MailAddress(ToMail, toName);

                System.Net.Mail.MailMessage message = new MailMessage(addressFrom, addressTo);
                message.Sender = new MailAddress(fromMail);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;
                message.Subject = subject;
                message.Body = mailContent;
                client.Send(message);
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
        }

    }
}
